$(function () {
    var userstring = sessionStorage.getItem('user');
    var user = JSON.parse(userstring);
    var nickname=user.nickname;
    var id=user.id
    $('#nickname').text(nickname);
    $.get("pc/address/find", {"uid": id}, function (result) {
        JSON.stringify(result);

        var a = result.status;
        var b = result.result;
        if (a == 400) {
            forList(b);
        } else {
            alert(b);
        }
        //通过user获取用户地址相关信息并显示下拉列表
    });

    $("[value='添加']").click(function () {
        alert("111")
        var sname = $("[name='sname']").val();
        var detailedAddress = $("[name='address']").val();
        var postalcode = $("[name='number']").val();
        var phone = $("[name='phone']").val();

        $.get("pc/address/addAddress", {
            "uid": id,
            "sname": sname,
            "detailedAddress": detailedAddress,
            "postalcode": postalcode,
            "phone": phone
        }, function (result) {
            var a = result.status;
            var b = result.result;
            if (a == 400) {
                alert("添加成功");
                forList(b);
            } else {
                alert(b);
            }
        })
    });

    var val = null;
    $("select").change(function () {
        val = $(this).find("option:selected").val();
    })//获取所选option的value值，即地址表id

    $("[value='修改']").click(function () {
        var sname = $("[name='sname']").val();
        var detailedAddress = $("[name='address']").val();
        var postalcode = $("[name='number']").val();
        var phone = $("[name='phone']").val();
        alert(val);
        alert(postalcode);
        $.get("pc/address/update", {
            "id": val,
            "uid": id,
            "sname": sname,
            "detailedAddress": detailedAddress,
            "postalcode": postalcode,
            "phone": phone
        }, function (result) {
            var a = result.status;
            var b = result.result;
            if (a == 400) {
                alert("修改成功");
                forList(b);
            } else {
                alert(b);
            }
        })
    })
    function forList(list){
        $("select").empty();
        $("<option value='-1'>请选择</option>>").appendTo("select");
        for (var i=0;i<list.length;i++){
            $("<option value='"+list[i].id+"'>"+list[i].detailedAddress +"&nbsp;"+"&nbsp;"+"&nbsp;"+
                list[i].postalcode+'号 '+"&nbsp;"+
                '('+list[i].sname+') '+"&nbsp;"+
                list[i].phone+"</option>\n").appendTo("select");
        }
        //循环添加下拉列表选项option至select标签
    }

})


